﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using MeetingMinutesManager.Form;

namespace MeetingMinutesManager
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            // Compose the error message
            String messageID = Request.Params["MSG_ID"];

            if (messageID == null)
            {
                return;
            }

            if (messageID.Equals("1"))
            {
                lblMsg.Text = "Please login first!";
            }
            else if (messageID.Equals("2"))
            {
                lblMsg.Text = "Access Denied";
            }
            else
            {
                lblMsg.Text = "Error happened. Login again!";
            }
        }

        protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
        {
            String userName = Login1.UserName.Trim();
            String password = Login1.Password.Trim();
            CheckBox rm = (CheckBox)Login1.FindControl("RememberMe");

            try
            {
                bool isAuthenticated = ResourceOperator.AuthenticateUser(userName, password);

                if (isAuthenticated == true)
                {
                    e.Authenticated = true;
                    Session["user_name"] = userName;
                    Session.Timeout = 480;

                    String role = ResourceOperator.ReadUserRole(userName);
                    Session["role"] = role;

                    Login1.DestinationPageUrl = "Default.aspx";
                }
                else
                {
                    e.Authenticated = false;
                }
            }
            catch (Exception ex)
            {
                Messenger.Show(Response, "Error: " + ex.Message);
                e.Authenticated = false;
            }
        }

        protected void btnRegister_Click(object sender, EventArgs e)
        {
            Response.Redirect("Register.aspx");
        }
    }
}
